import { login as loginApi, logout as logoutApi, getInfo, getUserMsg } from '@/api/auth'
import { getToken, setToken, removeToken } from '@/utils/auth'

// 模块级变量：用于缓存正在进行的VIP状态更新 Promise，防止重复调用
let updateVipStatusPromise = null

export default {
  namespaced: true,
  state: {
    token: getToken(),
    id: '',
    name: '',
    username: '',
    vip: 0,
    email: '',
    avatar: '',
    balance: '',
    rewardBalance: '',
    memberEnd: '',
    openId: '',
    userInfo: {
      name: '默认用户',
      age: 18,
    },
    // 新增用户详细信息字段
    userMsg: {
      nickname: '',
      createTime: '',
      avatarUrl: '',
      gender: '',
      points: 0,
      inviteCode: '',
      email: '',
      vip: 0,
      memberExpireDate: '',
      memberType: '',
    },
  },
  getters: {
    token: state => state.token,
    isLogin: state => !!state.token,
    ID: state => state.id,
    userName: state => state.email,
    userEmail: state => state.email,
    nickName: state => state.name,
    avatarImg: state => state.avatar,
    balanceWallet: state => state.balance,
    rewardWallet: state => state.rewardBalance,
    VIP: state => state.vip,
    wxOpenId: state => state.openId,
    memberEndTime: state => state.memberEnd,
    // 新增用户详细信息getters
    userNickname: state => state.userMsg.nickname,
    userCreateTime: state => state.userMsg.createTime,
    userAvatarUrl: state => state.userMsg.avatarUrl,
    userGender: state => state.userMsg.gender,
    userPoints: state => state.userMsg.points,
    userInviteCode: state => state.userMsg.inviteCode,
    userMsgInfo: state => state.userMsg,
    // VIP相关getters
    isVip: state => state.userMsg.vip === 1 || state.userMsg.vip === true,
    userVip: state => state.userMsg.vip,
    memberExpireDate: state => state.userMsg.memberExpireDate,
    memberType: state => state.userMsg.memberType,
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
      // 保存到本地存储，确保token持久化
      setToken(token)
    },
    SET_USER_INFO(state, userInfo) {
      // 合并更新，保留原有字段
      if (userInfo) {
        state.userInfo = {
          ...state.userInfo,
          ...userInfo,
          // 确保基本字段存在
          name: userInfo.nickname || userInfo.name || state.userInfo?.name || '默认用户',
          age: state.userInfo?.age || 18,
        }
        // 如果传入的是用户详细信息，也更新 userMsg
        if (userInfo.nickname || userInfo.points !== undefined) {
          state.userMsg = {
            nickname: userInfo.nickname || state.userMsg.nickname,
            createTime: userInfo.createTime || state.userMsg.createTime,
            avatarUrl: userInfo.avatarUrl || state.userMsg.avatarUrl,
            gender: userInfo.gender || state.userMsg.gender,
            points: userInfo.points !== undefined ? userInfo.points : state.userMsg.points,
            inviteCode: userInfo.inviteCode || state.userMsg.inviteCode,
            email: userInfo.email || state.userMsg.email,
            vip: userInfo.vip !== undefined ? userInfo.vip : state.userMsg.vip,
            memberExpireDate: userInfo.memberExpireDate || state.userMsg.memberExpireDate,
            memberType: userInfo.memberType || state.userMsg.memberType,
          }
        }
      }
    },
    SET_USER_DATA(state, data) {
      state.id = data.uid || data.id
      state.name = data.name
      state.vip = data.vip
      state.email = data.email
      state.avatar = data.avatar
      state.balance = data.balance
      state.rewardBalance = data.reward
      state.openId = data.openId
      state.memberEnd = data.memberEndTime
    },
    SET_NICK_NAME(state, name) {
      state.name = name
    },
    SET_AVATAR(state, avatar) {
      state.avatar = avatar
    },
    SET_VIP(state, vip) {
      state.vip = vip
    },
    // 新增设置用户详细信息的mutation
    SET_USER_MSG(state, userMsg) {
      state.userMsg = {
        nickname: userMsg.nickname || '',
        createTime: userMsg.createTime || '',
        avatarUrl: userMsg.avatarUrl || '',
        gender: userMsg.gender || '',
        points: userMsg.points || 0,
        inviteCode: userMsg.inviteCode || '',
        email: userMsg.email || '',
        vip: userMsg.vip || 0,
        memberExpireDate: userMsg.memberExpireDate || '',
        memberType: userMsg.memberType || '',
      }
      // 同时更新旧的 vip 字段，保持兼容性
      state.vip = userMsg.vip || 0
    },
    CLEAR_USER_INFO(state) {
      state.token = ''
      state.id = ''
      state.name = ''
      state.username = ''
      state.vip = 0
      state.email = ''
      state.avatar = ''
      state.balance = ''
      state.rewardBalance = ''
      state.memberEnd = ''
      state.openId = ''
      state.userInfo = null
      // 清除用户详细信息
      state.userMsg = {
        nickname: '',
        createTime: '',
        avatarUrl: '',
        gender: '',
        points: 0,
        inviteCode: '',
        email: '',
        vip: 0,
        memberExpireDate: '',
        memberType: '',
      }
      // 清除本地存储的token
      removeToken()
    },
  },
  actions: {
    // 登录
    async login({ commit, rootState }, userInfo) {
      try {
        const username = userInfo.username.trim()
        const response = await loginApi(userInfo)
        if (response.code !== 200) {
          return Promise.reject(response.message)
        }
        const data = response.data

        // 先清除旧的token，确保使用最新token
        if (rootState.token && rootState.token.token) {
          commit('token/CLEAR_TOKEN', null, { root: true })
        }
        
        // 设置新的token，这会同时更新user模块和token模块
        commit('SET_TOKEN', data.token)
        // 确保token模块也被更新
        if (rootState.token) {
          commit('token/SET_TOKEN', data.token, { root: true })
        }
        
        if (data.userInfo) {
          commit('SET_USER_DATA', data.userInfo)
        }

        return Promise.resolve(response)
      } catch (error) {
        console.error('登录失败：', error)
        return Promise.reject(error)
      }
    },

    // 获取用户信息
    async getUserInfo({ commit }) {
      try {
        const response = await getInfo()
        const data = response.data
        commit('SET_USER_DATA', data)
        return response
      } catch (error) {
        console.error('获取用户信息失败：', error)
        throw error
      }
    },

    // 获取用户详细信息 (新接口)
    async getUserMsg({ commit }) {
      try {
        const response = await getUserMsg()
        if (response.code === 200) {
          const data = response.data
          commit('SET_USER_MSG', data)
          return response
        } else {
          throw new Error(response.message || '获取用户信息失败')
        }
      } catch (error) {
        console.error('获取用户详细信息失败：', error)
        throw error
      }
    },

    // 前端登出
    async fedLogOut({ commit, rootState }) {
      try {
        await logoutApi()
        commit('CLEAR_USER_INFO')
        // 确保token模块也被清除
        if (rootState.token) {
          commit('token/CLEAR_TOKEN', null, { root: true })
        }
        return Promise.resolve()
      } catch (error) {
        // 即使 API 调用失败，也要清除本地数据
        commit('CLEAR_USER_INFO')
        // 确保token模块也被清除
        if (rootState.token) {
          commit('token/CLEAR_TOKEN', null, { root: true })
        }
        return Promise.resolve()
      }
    },

    // 重置 token
    resetToken({ commit, rootState }) {
      commit('CLEAR_USER_INFO')
      // 确保token模块也被清除
      if (rootState.token) {
        commit('token/CLEAR_TOKEN', null, { root: true })
      }
      return Promise.resolve()
    },

    // 设置昵称
    setNickName({ commit }, name) {
      commit('SET_NICK_NAME', name)
    },

    // 设置头像
    setAvatar({ commit }, avatar) {
      commit('SET_AVATAR', avatar)
    },

    // 设置 VIP 状态
    setVip({ commit }, vip) {
      commit('SET_VIP', vip)
    },

    // 统一更新VIP状态（从服务器获取最新状态）
    // 使用模块级变量缓存 Promise，防止重复调用
    async updateVipStatus({ commit, state }) {
      try {
        // 如果没有token，不更新
        if (!state.token) {
          return Promise.resolve()
        }

        // 如果正在更新中，返回同一个 Promise，避免重复请求
        if (updateVipStatusPromise) {
          return updateVipStatusPromise
        }

        // 创建更新 Promise
        updateVipStatusPromise = (async () => {
          try {
            const response = await getUserMsg()
            if (response.code === 200 && response.data) {
              const isVip = response.data.vip === 1 || response.data.vip === true
              commit('SET_VIP', isVip ? 1 : 0)

              // 同时更新用户详细信息到store（包含 vip 字段）
              commit('SET_USER_MSG', {
                nickname: response.data.nickname || '',
                createTime: response.data.createTime || '',
                avatarUrl: response.data.avatarUrl || '',
                gender: response.data.gender || '',
                points: response.data.points || 0,
                inviteCode: response.data.inviteCode || '',
                email: response.data.email || '',
                vip: response.data.vip || 0,
                memberExpireDate: response.data.memberExpireDate || '',
                memberType: response.data.memberType || '',
              })

              // 更新用户信息（包含 memberExpireDate 和 memberType）
              commit('SET_USER_INFO', {
                nickname: response.data.nickname || '',
                createTime: response.data.createTime || '',
                avatarUrl: response.data.avatarUrl || '',
                gender: response.data.gender || '',
                points: response.data.points || 0,
                inviteCode: response.data.inviteCode || '',
                email: response.data.email || '',
                vip: response.data.vip || 0,
                memberExpireDate: response.data.memberExpireDate || '',
                memberType: response.data.memberType || '',
              })
              
              console.log('VIP状态已更新:', isVip)
              return { isVip }
            }
            return null
          } catch (error) {
            console.error('更新VIP状态失败:', error)
            throw error
          } finally {
            // 清除 Promise 缓存，允许下次更新
            updateVipStatusPromise = null
          }
        })()

        return await updateVipStatusPromise
      } catch (error) {
        // 失败时不抛出错误，避免影响页面正常显示
        updateVipStatusPromise = null
        return Promise.resolve()
      }
    },
  },
}
